import os
from managers.commHAL import *
from managers.MotionFactory import *
from managers.motion import *
from managers.vhd import *
from managers.agent import *

class SystemCam:
	port = 9000

	def __init__(self,camid='',tipus='',enabled=0,fps=0.0,mode=0,nom='',threshold=0.5,port=0):
		self.camid = camid
		self.tipus = tipus
		self.enabled = enabled
		self.fps = fps
		self.mode = mode
		self.nom = nom
		self.threshold = threshold
		self.port = port
	
	def getContent(self):
		c = {}
		c['camid'] = self.camid
		c['tipus'] = self.tipus
		c['enabled'] = str(self.enabled)
		c['fps'] = str(self.fps)
		c['mode'] = str(self.mode)
		c['nom'] = self.nom
		c['threshold'] = str(self.threshold)
		c['port'] = str(self.port)
		return c

	def save(self,agent):
 		print '!!!!!!!!!!!',self.threshold
		s = "REPLACE INTO Cameras VALUES ('%s','%s',%d,%f,%d,'%s',%f,%d) "%(self.camid,self.tipus,self.enabled,self.fps,self.mode,self.nom,self.threshold,self.port)
		db = agent.getDBManager()
		db.query(s)

		print "cams::saved ", self.camid
		

	def configure(self,agent):
		if self.enabled:
			print "AVILITADA"
			awd = agent.getWorkDir()
			#Montatge del Disc Dur Virtual
			if not ismount(awd + self.camid):
				tmp_dir = "/tmp/"+self.camid
				os.system("mkdir -p "+tmp_dir)
				mount(awd + self.camid,'ext3',tmp_dir)
				print "montat! => "+ awd + self.camid +" - "+tmp_dir
			else:
				print "Ja es troba montat!"

			#Creacio de la factoria
			mf = agent.getMotionFactory()
			mf.Modificar_Tot(self.camid,int(self.fps), 320, 240,int(self.mode), awd,60,60,float(self.threshold),awd+'on_movie_start.py '+self.camid+' %t',awd+'on_movie_end.py '+self.camid+' %t',int(self.port),int(self.port),self.nom,int(agent.MaxDuration))
			print "FITXER GENERAT: ", awd+self.camid+'.conf'
			mf.Generar_MotionFile(self.camid,awd+self.camid+'.conf')
			print "port=",self.port
			# TODO: Revisar este campo, porque no mata nada (falta activar los motions por algun lado?)
			# mf.Reconfigurar_Motion(int(self.port)) 

	def init(self, agent):
		try:
			awd = agent.getWorkDir()
			print "Add Camera ",awd
			os.system("mkdir -p " + awd )
			create(awd + self.camid, agent.MaxSpace)
			format(awd + self.camid, 'ext3')

#			print "Entrant a MotionConfig IDHW=",self.camid
#			mf = agent.getMotionFactory()
#			mf.newCamera(self.camid,int(self.fps), 320, 240,int(self.mode), awd,60,60,float(self.threshold),awd+'on_movie_start.py '+self.camid+' %t',awd+'on_movie_end.py '+self.camid+' %t',int(self.port),int(self.port),self.nom)#,int(agent.MaxDuration))
#			print "FITXER GENERAT: ", awd+self.camid+'.conf'
#			mf.Generar_MotionFile(self.camid,awd+self.camid+'.conf')
			# TODO: Revisar este campo, porque no mata nada (falta activar los motions por algun lado?)
			# mf.Reconfigurar_Motion(int(self.port)) 
			
			s = "INSERT INTO Cameras VALUES ('%s','%s',%d,%f,%d,'%s',%f,%d) "%(self.camid,self.tipus,self.enabled,self.fps,self.mode,self.nom,self.threshold,self.port)
			db = agent.getDBManager()
			db.query(s)
		
			print "cams::iniciat ", self.camid
		except:
			print "cams::AddCamera error!"
			return False

	@staticmethod
	def getNewPort(db):
		info = db.query("SELECT MAX(port) FROM Cameras")
		if info[0][0]!=None:
			return int(info[0][0])+1
		else:
			return SystemCam.port

	@staticmethod
	def buildFromReg(info):
		cam = SystemCam(info[0],info[1],info[2],info[3],info[4],info[5],info[6],info[7])
		return cam
		
	@staticmethod
	def getFromId(db, camid):
		info = db.query("SELECT * FROM Cameras WHERE IdHW='%s'"%(camid))
		return SystemCam.buildFromReg(info[0])

	@staticmethod
	def getList(db):
		list = db.query("SELECT * FROM Cameras")
		cams = []
		for elem in list:
			cams.append(SystemCam.buildFromReg(elem))
		return cams

	@staticmethod
	def getConnected(db):
		list = db.query("SELECT * FROM Cameras Where Type='conn'")
		cams = []
		for elem in list:
			cams.append(SystemCam.buildFromReg(elem))
		return cams

	@staticmethod
	def existsCamera(db, camid):
		res = db.query("SELECT COUNT(*) FROM Cameras WHERE IdHW='%s'"%(camid))
		return res[0][0]>0

	@staticmethod
	def setDisconnect(db):
		db.query("UPDATE Cameras SET Type='dis'")

